<template>
  <div class="rider-home">
    <div class="dashboard-header">
      <h1>骑手工作台</h1>
      <div class="grab-order-status">
        <span>抢单模式：</span>
        <el-switch
          v-model="grabOrderEnabled"
          active-text="开启"
          inactive-text="关闭"
          active-color="#13ce66"
          @change="toggleGrabOrderStatus">
        </el-switch>
      </div>
    </div>
    
    <!-- 抢单状态提示 -->
    <el-alert
      v-if="grabOrderEnabled"
      title="您已开启抢单模式，可以在下方查看并抢接待配送订单"
      type="success"
      show-icon
      :closable="false">
    </el-alert>
    <el-alert
      v-else
      title="您当前未开启抢单模式，请开启后查看可抢订单"
      type="info"
      show-icon
      :closable="false">
    </el-alert>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="8">
        <el-card shadow="hover" class="status-card" v-loading="statsLoading">
          <div slot="header">
            <span>今日接单</span>
          </div>
          <div class="card-content">
            <h2>{{ stats.todayOrders || 0 }}</h2>
            <span>单</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="status-card" v-loading="statsLoading">
          <div slot="header">
            <span>今日收入</span>
          </div>
          <div class="card-content">
            <h2>{{ stats.todayIncome || 0 }}</h2>
            <span>元</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="status-card" v-loading="statsLoading">
          <div slot="header">
            <span>配送中</span>
            <el-tooltip content="配送中的订单数量" placement="top">
              <i class="el-icon-info" style="margin-left: 5px; cursor: help;"></i>
            </el-tooltip>
          </div>
          <div class="card-content">
            <h2>{{ stats.inProgressOrders || 0 }}</h2>
            <span>单</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 等待接单区域 - 优先显示，并添加醒目的标题 -->
    <el-card v-if="grabOrderEnabled" shadow="hover" class="waiting-orders" style="margin-bottom: 20px;">
      <div slot="header" class="card-header">
        <div class="header-title">
          <i class="el-icon-bell"></i>
          <span>可抢订单</span>
        </div>
        <div>
          <el-button type="primary" icon="el-icon-refresh" size="small" @click="refreshWaitingOrders">刷新订单</el-button>
          <el-button type="text" @click="viewAllAvailableOrders">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
      </div>
      <el-table :data="waitingOrders" style="width: 100%" v-loading="waitingLoading" highlight-current-row>
        <el-table-column prop="orderNumber" label="订单号" width="150"></el-table-column>
        <el-table-column label="商家" width="150">
          <template slot-scope="scope">
            {{ scope.row.merchantName || scope.row.merchant_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送地址"></el-table-column>
        <el-table-column label="金额" width="80">
          <template slot-scope="scope">
            {{ scope.row.payAmount ? '¥' + scope.row.payAmount : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="grabOrder(scope.row)">抢单</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="empty-data" v-if="waitingOrders.length === 0 && !waitingLoading">
        <el-empty description="暂无待接单的订单"></el-empty>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="recent-orders" v-loading="loading">
      <div slot="header" class="card-header">
        <div class="header-title">
          <i class="el-icon-bicycle"></i>
          <span>正在配送的订单</span>
        </div>
        <el-button type="text" @click="viewAllOrders">查看全部 <i class="el-icon-arrow-right"></i></el-button>
      </div>
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="150"></el-table-column>
        <el-table-column label="商家" width="150">
          <template slot-scope="scope">
            {{ scope.row.merchantName || scope.row.merchant_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送地址"></el-table-column>
        <el-table-column label="金额" width="80">
          <template slot-scope="scope">
            {{ scope.row.payAmount ? '¥' + scope.row.payAmount : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewOrderDetail(scope.row)">查看</el-button>
            <el-button size="mini" type="success" @click="completeOrder(scope.row)">完成</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="empty-data" v-if="recentOrders.length === 0 && !loading">
        <el-empty description="暂无配送中的订单"></el-empty>
      </div>
    </el-card>
    
    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="50%">
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="商品总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="配送费">¥{{ currentOrder.deliveryFee || 0 }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
          <el-descriptions-item label="下单时间" :span="2">{{ formatDate(currentOrder.createdTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentOrder.remarks || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <h3>订单商品</h3>
        <el-table :data="orderItems" style="width: 100%">
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="success" v-if="currentOrder && currentOrder.status === 2" @click="completeOrderInDialog">完成配送</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getInProgressOrders,
  getAvailableOrders,
  takeOrder,
  completeOrder,
  getGrabOrderStatus,
  toggleGrabOrderStatus,
  getRiderStats
} from '@/api/rider';
import { mapState } from 'vuex';

export default {
  name: 'RiderHome',
  data() {
    return {
      loading: false,
      statsLoading: false,
      waitingLoading: false,
      stats: {
        todayOrders: 0,
        todayIncome: 0,
        inProgressOrders: 0
      },
      recentOrders: [],
      waitingOrders: [],
      grabOrderEnabled: false,
      currentOrder: null,
      orderItems: [],
      dialogVisible: false
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created() {
    this.loadDashboard();
    this.checkGrabOrderStatus();
    // 定时刷新可抢订单列表 (30秒刷新一次)
    this.refreshInterval = setInterval(() => {
      if (this.grabOrderEnabled) {
        this.loadWaitingOrders();
      }
    }, 30000);
  },
  beforeDestroy() {
    // 清除定时器
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  },
  methods: {
    // 加载仪表盘数据
    loadDashboard() {
      this.loading = true;
      this.statsLoading = true;
      
      // 获取正在配送的订单 - 先获取准确的配送中订单数量
      this.loadInProgressOrders(() => {
        // 完成加载配送中订单后，再获取其他统计数据
        this.loadRiderStats();
      });
    },
    
    // 加载骑手统计数据
    loadRiderStats() {
      const riderId = this.userInfo.id;
      
      getRiderStats(riderId).then(res => {
        if (res.code === 200) {
          // 合并统计数据，保留原有配送中订单数
          const inProgressCount = this.stats.inProgressOrders;
          this.stats = {
            ...res.data,
            inProgressOrders: inProgressCount // 使用从loadInProgressOrders获取的准确数量
          };
        } else {
          console.error('获取骑手统计数据失败:', res.message);
        }
      }).catch(err => {
        console.error('获取骑手统计数据失败', err);
      }).finally(() => {
        this.statsLoading = false;
      });
    },
    
    // 加载配送中订单
    loadInProgressOrders(callback) {
      const riderId = this.userInfo.id;
      const params = { page: 1, size: 100 }; // 获取足够多的订单以确保统计准确
      
      getInProgressOrders(riderId, params).then(res => {
        if (res.code === 200) {
          // 先设置显示订单列表（只显示前5个）
          this.recentOrders = (res.data.records || []).slice(0, 5);
          
          // 更新统计数据 - 记录准确的配送中订单数量
          this.stats.inProgressOrders = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取订单数据失败');
        }
      }).catch(err => {
        console.error('获取配送中订单失败', err);
      }).finally(() => {
        this.loading = false;
        // 如果有回调函数，执行它
        if (typeof callback === 'function') {
          callback();
        }
      });
    },
    
    // 加载待接单列表
    loadWaitingOrders() {
      if (!this.grabOrderEnabled) return;
      
      this.waitingLoading = true;
      const params = { page: 1, size: 5 };
      
      getAvailableOrders(params).then(res => {
        if (res.code === 200) {
          this.waitingOrders = res.data.records || [];
        } else {
          this.$message.error(res.message || '获取待接单列表失败');
        }
      }).catch(err => {
        console.error('获取待接单列表失败', err);
      }).finally(() => {
        this.waitingLoading = false;
      });
    },
    
    // 查看骑手抢单状态
    checkGrabOrderStatus() {
      const riderId = this.userInfo.id;
      
      getGrabOrderStatus(riderId).then(res => {
        if (res.code === 200) {
          this.grabOrderEnabled = res.data === 1;
          if (this.grabOrderEnabled) {
            this.loadWaitingOrders();
          }
        }
      }).catch(err => {
        console.error('获取抢单状态失败', err);
      });
    },
    
    // 切换抢单状态
    toggleGrabOrderStatus(status) {
      const riderId = this.userInfo.id;
      const value = status ? 1 : 0;
      
      toggleGrabOrderStatus(riderId, value).then(res => {
        if (res.code === 200) {
          this.$message.success(res.data || '切换成功');
          this.grabOrderEnabled = status;
          
          if (status) {
            this.loadWaitingOrders();
          }
        } else {
          this.$message.error(res.message || '切换失败');
          this.grabOrderEnabled = !status; // 恢复原状态
        }
      }).catch(err => {
        console.error('切换抢单状态失败', err);
        this.grabOrderEnabled = !status; // 恢复原状态
      });
    },
    
    // 骑手抢单
    grabOrder(order) {
      this.$confirm('确认抢单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const riderId = this.userInfo.id;
        
        takeOrder(order.id, riderId).then(res => {
          if (res.code === 200) {
            this.$message.success('抢单成功');
            // 更新数据
            this.loadWaitingOrders();
            // 先更新配送中订单，再加载统计数据
            this.loadInProgressOrders(() => {
              this.loadRiderStats();
            });
          } else {
            this.$message.error(res.message || '抢单失败');
          }
        }).catch(err => {
          console.error('抢单失败', err);
          this.$message.error('抢单失败');
        });
      }).catch(() => {});
    },
    
    // 完成订单配送
    completeOrder(order) {
      this.$confirm('确认已完成配送？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const riderId = this.userInfo.id;
        
        completeOrder(order.id, riderId).then(res => {
          if (res.code === 200) {
            this.$message.success('订单已完成');
            // 先更新配送中订单，再加载统计数据
            this.loadInProgressOrders(() => {
              this.loadRiderStats();
            });
          } else {
            this.$message.error(res.message || '操作失败');
          }
        }).catch(err => {
          console.error('完成订单失败', err);
          this.$message.error('操作失败');
        });
      }).catch(() => {});
    },
    
    // 查看所有订单
    viewAllOrders() {
      this.$router.push('/rider/order');
    },
    
    // 查看所有可抢订单
    viewAllAvailableOrders() {
      this.$router.push({
        path: '/rider/order',
        query: { tab: 'available' }
      });
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      this.currentOrder = order;
      this.orderItems = [];
      
      // 解析商品数据
      try {
        if (order.items) {
          this.orderItems = JSON.parse(order.items);
        }
      } catch (e) {
        console.error('解析订单商品数据失败', e);
      }
      
      this.dialogVisible = true;
    },
    
    // 刷新待接单列表
    refreshWaitingOrders() {
      this.loadWaitingOrders();
    },
    
    // 在弹窗中完成订单
    completeOrderInDialog() {
      if (this.currentOrder) {
        this.completeOrder(this.currentOrder);
        this.dialogVisible = false;
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      };
      return typeMap[status] || '';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleString();
    }
  }
}
</script>

<style scoped>
.rider-home {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.grab-order-status {
  display: flex;
  align-items: center;
}

.grab-order-status span {
  margin-right: 10px;
  font-size: 16px;
  font-weight: 500;
}

.status-card {
  margin-bottom: 20px;
}

.card-content {
  display: flex;
  align-items: baseline;
}

.card-content h2 {
  font-size: 36px;
  margin: 0 10px 0 0;
  color: #409EFF;
}

.recent-orders, .waiting-orders {
  margin-bottom: 20px;
}

.empty-data {
  margin: 20px 0;
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title i {
  margin-right: 5px;
  font-size: 18px;
}

.header-title span {
  font-size: 16px;
  font-weight: 500;
}

.waiting-orders {
  border: 1px solid #67c23a;
}

.waiting-orders .el-card__header {
  background-color: #f0f9eb;
  color: #67c23a;
}
</style> 